package network;

import static java.net.InetAddress.getLocalHost;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

	private String id;
	private Socket socket;
	private boolean isConnected;

	public Client() {
		id = "Anonymous Client";
	}

	public Client(InetAddress host, int port) throws IOException {
		this();
		socket = new Socket(host, port);
		isConnected = true;
	}

	public Client(String id, InetAddress address, int port) throws IOException {
		this(address, port);
		this.id = id;
	}

	private void writerStringStream() {
		String end = "END";
		BufferedWriter buf = null;
		try {
			buf = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			for (int i = 0; i < 10; i++) {
				buf.write(id + ":" + i + "\n");
				buf.flush();
				Thread.sleep(500);
				readerStringStream();
			}
			buf.write(end);
			buf.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void readerStringStream() {
		try {
			BufferedReader buf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String read = "";
			if (isConnected) {
				read = buf.readLine();
				if (read.compareTo("END") == 0) {
					isConnected = false;
					socket.close();
				}
				System.out.println(read);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		try {
			Client client = new Client(getLocalHost(), 8000);
			client.writerStringStream();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
